<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'
import { Api } from '@/api'

const router = useRouter()
const activeTab = ref('questionnaires')
const loading = ref(false)
const questionnaires = ref([])
const scoreRanges = ref([])

// 问卷表单相关
const dialogVisible = ref(false)
const questionnaireForm = ref({
  id: '',
  title: '',
  ps_introduction: '',
  scoring: ''
})

// 当前选中的问卷ID
const currentQuestionnaireId = ref(null)

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取问卷列表
const loadQuestionnaires = async () => {
  try {
    loading.value = true
    const response = await Api.getQuestionnaireList()
    if (response.data && Array.isArray(response.data.data)) {
      questionnaires.value = response.data.data
    }
  } catch (err) {
    console.error('加载问卷列表失败:', err)
    ElMessage.error('加载问卷列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分数段列表
const loadScoreRanges = async () => {
  try {
    loading.value = true
    const response = await Api.getQuestionScoreRanges()
    if (response.data && Array.isArray(response.data.data)) {
      scoreRanges.value = response.data.data
    }
  } catch (err) {
    console.error('加载分数段列表失败:', err)
    ElMessage.error('加载分数段列表失败')
  } finally {
    loading.value = false
  }
}

// 删除问卷
const handleDeleteQuestionnaire = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个问卷吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await Api.deleteQuestionnaire({ id })
    ElMessage.success('删除成功')
    loadQuestionnaires()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除失败:', err)
      ElMessage.error('删除失败')
    }
  }
}

// 删除分数段
const handleDeleteScoreRange = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分数段吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await Api.deleteQuestionScoreRange({ id })
    ElMessage.success('删除成功')
    loadScoreRanges()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除失败:', err)
      ElMessage.error('删除失败')
    }
  }
}

// 创建问卷
const createQuestionnaire = async () => {
  try {
    if (!questionnaireForm.value.title.trim()) {
      ElMessage.warning('请输入问卷标题')
      return
    }
    const response = await Api.createQuestionnaire({
      title: questionnaireForm.value.title,
      description: questionnaireForm.value.ps_introduction,
      scoring: questionnaireForm.value.scoring
    })
    if (response.data && response.data.status === 201) {
      ElMessage.success('创建问卷成功')
      dialogVisible.value = false
      loadQuestionnaires()
      // 清空表单
      questionnaireForm.value = {
        id: '',
        title: '',
        ps_introduction: '',
        scoring: ''
      }
    }
  } catch (err) {
    console.error('创建问卷失败:', err)
    ElMessage.error('创建问卷失败')
  }
}

// 更新问卷
const updateQuestionnaire = async () => {
  try {
    if (!questionnaireForm.value.title.trim()) {
      ElMessage.warning('请输入问卷标题')
      return
    }
    const response = await Api.updateQuestionnaire({
      id: questionnaireForm.value.id,
      title: questionnaireForm.value.title,
      description: questionnaireForm.value.ps_introduction,
      scoring: questionnaireForm.value.scoring
    })
    if (response.data && response.data.status === 200) {
      ElMessage.success('更新问卷成功')
      dialogVisible.value = false
      loadQuestionnaires()
      // 清空表单
      questionnaireForm.value = {
        id: '',
        title: '',
        ps_introduction: '',
        scoring: ''
      }
    }
  } catch (err) {
    console.error('更新问卷失败:', err)
    ElMessage.error('更新问卷失败')
  }
}

// 文件上传相关
const questionsFileInput = ref(null)
const scoreRangesFileInput = ref(null)
const questionScoreRangeFileInput = ref(null)

// 处理题目文件上传
const handleQuestionsUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!currentQuestionnaireId.value) {
    ElMessage.warning('请先选择要导入题目的问卷')
    return
  }

  const formData = new FormData()
  formData.append('file', file)
  formData.append('questionnaire_id', currentQuestionnaireId.value)

  try {
    loading.value = true
    const response = await Api.uploadXlsxQuestions(formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    if (response.data && response.data.status === 200) {
      ElMessage.success('题目导入成功')
      loadQuestionnaires()
    }
  } catch (err) {
    console.error('题目导入失败:', err)
    ElMessage.error('题目导入失败: ' + (err.response?.data?.message || err.message || '未知错误'))
  } finally {
    loading.value = false
    event.target.value = ''
  }
}

// 处理问卷分数段文件上传
const handleQuestionScoreRangeUpload = async (event, questionnaireId) => {
  const file = event.target.files[0]
  if (!file) return

  const formData = new FormData()
  formData.append('file', file)
  formData.append('questionnaire_id', questionnaireId)

  try {
    loading.value = true
    const response = await Api.importQuestionScoreRanges(formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    if (response.data && response.data.status === 200) {
      ElMessage.success('分数段导入成功')
      loadScoreRanges()
    }
  } catch (err) {
    console.error('分数段导入失败:', err)
    ElMessage.error('分数段导入失败: ' + (err.response?.data?.message || err.message || '未知错误'))
  } finally {
    loading.value = false
    event.target.value = ''
  }
}

// 打开文件选择对话框
const openQuestionsUpload = (questionnaireId) => {
  currentQuestionnaireId.value = questionnaireId
  questionsFileInput.value.click()
}

// 打开分数段文件选择对话框
const openScoreRangeUpload = (questionnaireId) => {
  currentQuestionnaireId.value = questionnaireId
  questionScoreRangeFileInput.value.click()
}

// 下载模板
const downloadTemplate = (type) => {
  let templateContent = ''
  let filename = ''

  switch (type) {
    case 'questionnaire':
      templateContent = '问卷标题,问卷描述\n示例问卷,这是一个示例问卷'
      filename = '问卷导入模板.csv'
      break
    case 'questions':
      templateContent = '题目内容,选项A,选项B,选项C,选项D,正确答案,分值\n示例题目,选项A,选项B,选项C,选项D,A,10'
      filename = '题目导入模板.csv'
      break
    case 'scoreRanges':
      templateContent = '问卷ID,最低分,最高分,心理状态,建议\n1,0,10,正常,保持良好心态\n1,11,20,轻度焦虑,建议适当放松'
      filename = '分数段导入模板.csv'
      break
  }

  const blob = new Blob([templateContent], { type: 'text/csv' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 处理分数段文件上传
const handleScoreRangesUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  const formData = new FormData()
  formData.append('file', file)

  try {
    loading.value = true
    const response = await Api.importQuestionScoreRanges(formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    if (response.data && response.data.status === 200) {
      ElMessage.success('分数段导入成功')
      loadScoreRanges()
    }
  } catch (err) {
    console.error('分数段导入失败:', err)
    ElMessage.error('分数段导入失败: ' + (err.response?.data?.message || err.message || '未知错误'))
  } finally {
    loading.value = false
    event.target.value = ''
  }
}

onMounted(() => {
  loadQuestionnaires()
})
</script>

<template>
  <div class="test-manage">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <el-icon><ArrowLeft /></el-icon>
      返回
    </div>

    <h1>心理问卷管理</h1>

    <el-tabs v-model="activeTab" @tab-click="(tab) => {
      if (tab.props.name === 'scoreRanges') loadScoreRanges()
    }">
      <!-- 问卷管理 -->
      <el-tab-pane label="问卷管理" name="questionnaires">
        <div class="toolbar">
          <el-button type="primary" @click="dialogVisible = true">创建问卷</el-button>
          <el-button type="info" @click="() => downloadTemplate('questions')">下载题目模板</el-button>
        </div>

        <el-table :data="questionnaires" v-loading="loading" border>
          <el-table-column prop="title" label="问卷标题" />
          <el-table-column prop="ps_introduction" label="问卷描述" />
          <el-table-column label="操作" width="300">
            <template #default="{ row }">
              <div class="button-group">
                <input
                  type="file"
                  ref="questionsFileInput"
                  style="display: none"
                  accept=".xlsx,.xls"
                  @change="handleQuestionsUpload"
                >
                <input
                  type="file"
                  ref="questionScoreRangeFileInput"
                  style="display: none"
                  accept=".xlsx,.xls"
                  @change="(event) => handleQuestionScoreRangeUpload(event, row.id)"
                >
                <el-button
                  type="primary"
                  size="small"
                  @click="openQuestionsUpload(row.id)"
                >
                  导入题目
                </el-button>
                <el-button
                  type="success"
                  size="small"
                  @click="openScoreRangeUpload(row.id)"
                >
                  导入分数段
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="() => handleDeleteQuestionnaire(row.id)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 分数段管理 -->
      <el-tab-pane label="分数段管理" name="scoreRanges">
        <div class="toolbar">
          <input type="file" ref="scoreRangesFileInput" style="display: none" @change="handleScoreRangesUpload">
          <el-button type="primary" @click="scoreRangesFileInput.value.click()">导入分数段</el-button>
          <el-button type="info" @click="() => downloadTemplate('scoreRanges')">下载模板</el-button>
        </div>

        <el-table :data="scoreRanges" v-loading="loading" border>
          <el-table-column prop="questionnaire_id" label="问卷ID" />
          <el-table-column prop="score_min" label="最低分" />
          <el-table-column prop="score_max" label="最高分" />
          <el-table-column prop="mental_status" label="心理状态" />
          <el-table-column prop="advice" label="建议" />
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="() => handleDeleteScoreRange(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建问卷对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="创建问卷"
      width="50%"
    >
      <el-form :model="questionnaireForm" label-width="100px">
        <el-form-item label="问卷标题" required>
          <el-input v-model="questionnaireForm.title" placeholder="请输入问卷标题"></el-input>
        </el-form-item>
        <el-form-item label="问卷描述">
          <el-input
            v-model="questionnaireForm.ps_introduction"
            type="textarea"
            rows="4"
            placeholder="请输入问卷描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createQuestionnaire">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.test-manage {
  padding: 20px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
  margin-bottom: 20px;
  transition: color 0.3s ease;
}

.back-button:hover {
  color: #66b1ff;
}

.back-button .el-icon {
  font-size: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.button-group {
  display: flex;
  gap: 8px;
  justify-content: center;
}

h1 {
  margin-bottom: 20px;
  color: #333;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
